package com.graduation.service;

import com.graduation.dao.UserDao;
import com.graduation.entity.User;
import com.graduation.util.DateUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Transactional
    @Override
    public Integer userRegister(User user) {
        //获取时间
        user.setRegistertime(DateUtil.getCurrentDate());
        Integer result = userDao.userRegister(user);
        return result;
    }

    /**
     * 查询用户是否存在
     * @param email
     * @return
     */
    @Override
    public Integer isExitsUser(String email) {
        return userDao.isExitsUser(email);
    }

    /**
     * 用户登录
     * @param email
     * @param password
     * @return
     */
    @Override
    public Integer loginSystem(HttpServletRequest request, HttpServletResponse response,
                               String email, String password, String state) {
        Integer integer = userDao.loginSystem(email, password);
        //校验成功
        if(integer == 1){
            User user = new User();
            user.setEmail(email);
            user.setPassword(password);
            request.getSession().setAttribute("user",user);
            //判断用户是否选择了记住密码
            if("on".equals(state) || state != null){
                //发送自动登录的cookie
                Cookie cookie = new Cookie("autoLogin",email + "-" + password);
                //设置7天免登录
                cookie.setMaxAge(60*60*24*7);
                //请求地址
                cookie.setPath(request.getContextPath());
                //放入到响应对象发送到客户端
                response.addCookie(cookie);
            }
            return 1;
        }
        else{
            request.setAttribute("errMsg","用户名或者密码错误");
            return 0;
        }
    }

    /**
     *
     * @param email
     * @return 返回用户的json格式的数据
     */
    @Override
    public User findUserById(String email) {
        User userById = userDao.findUserById(email);
        if(userById.getAddress() == null){
            userById.setAddress("尚未完善地址");
        }
        if(userById.getState() == null){
            userById.setState("普通用户");
        }
        return userById;
    }

    @Override
    public Integer updateUserBaseInfo(User user) {
        Integer integer = userDao.updateUserBaseInfo(user);
        return integer;
    }

    @Override
    public User findUserAddrAndName(String email) {
        return userDao.findUserAddrAndName(email);
    }
}
